<template>
  <div class="app-container">
    <el-card class="search-wrapper">
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item>
          <el-input
            v-model="queryParams.keyword"
            placeholder="充值单号/黑卡卡号"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-select v-model="queryParams.status" placeholder="充值状态" clearable>
            <el-option label="充值中" value="pending" />
            <el-option label="成功" value="success" />
            <el-option label="失败" value="failed" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="queryParams.verify_status" placeholder="核实状态" clearable>
            <el-option label="未核实" :value="0" />
            <el-option label="已核实" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="queryParams.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
          <el-button type="success" @click="handleAdd">新增充值</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-wrapper">
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        border
      >
        <el-table-column prop="recharge_no" label="充值单号" width="180" />
        <el-table-column prop="black_card_no" label="黑卡卡号" width="180" />
        <el-table-column label="充值类型" width="100">
          <template #default="scope">
            {{ scope.row.recharge_type === 'personal' ? '个人' : '机构' }}
          </template>
        </el-table-column>
        <el-table-column prop="org_name" label="所属机构" width="180">
          <template #default="scope">
            {{ scope.row.organization?.company_name || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="充值金额" width="120">
          <template #default="scope">
            {{ formatAmount(scope.row.amount) }}
          </template>
        </el-table-column>
        <el-table-column label="支付方式" width="100">
          <template #default="scope">
            {{ scope.row.payment_method === 'bank' ? '对公' : '其他' }}
          </template>
        </el-table-column>
        <el-table-column prop="payment_account" label="付款账号" width="150" show-overflow-tooltip />
        <el-table-column prop="payment_bank" label="付款银行" width="150" show-overflow-tooltip />
        <el-table-column prop="payment_time" label="付款时间" width="180" />
        <el-table-column label="核实状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.verify_status ? 'success' : 'warning'">
              {{ scope.row.verify_status ? '已核实' : '未核实' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="verify_time" label="核实时间" width="180" />
        <el-table-column prop="effect_time" label="生效时间" width="180" />
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              v-if="scope.row.status === 'pending'"
              type="primary"
              link
              @click="handleVerify(scope.row)"
            >
              核实
            </el-button>
            <el-button
              v-if="scope.row.status === 'pending'"
              type="danger"
              link
              @click="handleCancel(scope.row)"
            >
              取消
            </el-button>
            <el-button
              type="primary"
              link
              @click="handleDetail(scope.row)"
            >
              详情
            </el-button>
            <el-button
              type="primary"
              link
              @click="handleRecharge(scope.row)"
            >
              充值
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.limit"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 表单弹窗 -->
    <recharge-form
      v-model:visible="formVisible"
      @success="handleSuccess"
    />
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import RechargeForm from './RechargeForm.vue'
import { useRouter } from 'vue-router'

// 获取 router 实例
const router = useRouter()

// 查询参数
const queryParams = reactive({
  page: 1,
  limit: 10,
  keyword: '',
  status: '',
  verify_status: '',
  dateRange: []
})

// 表格数据
const loading = ref(false)
const tableData = ref([])
const total = ref(0)

// 表单弹窗控制
const formVisible = ref(false)

// 格式化金额
const formatAmount = (amount) => {
  return amount ? `¥${Number(amount).toFixed(2)}` : '¥0.00'
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    pending: 'warning',
    success: 'success',
    failed: 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    pending: '充值中',
    success: '成功',
    failed: '失败'
  }
  return textMap[status] || status
}

// 获取列表数据
const getList = async () => {
  loading.value = true
  try {
    const params = {
      ...queryParams,
      start_time: queryParams.dateRange?.[0],
      end_time: queryParams.dateRange?.[1]
    }
    delete params.dateRange

    const res = await request.get('/black-card/recharge/list', { params })
    tableData.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取列表失败：', error)
  }
  loading.value = false
}

// 搜索
const handleSearch = () => {
  queryParams.page = 1
  getList()
}

// 重置搜索
const resetQuery = () => {
  queryParams.keyword = ''
  queryParams.status = ''
  queryParams.verify_status = ''
  queryParams.dateRange = []
  handleSearch()
}

// 分页
const handleSizeChange = (val) => {
  queryParams.limit = val
  getList()
}

const handleCurrentChange = (val) => {
  queryParams.page = val
  getList()
}

// 新增
const handleAdd = () => {
  formVisible.value = true
}

// 核实
const handleVerify = (row) => {
  ElMessageBox.confirm(
    '确认要核实该充值记录吗？核实后将更新黑卡余额。',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await request.post('/black-card/recharge/verify', {
        recharge_id: row.recharge_id
      })
      ElMessage.success('核实成功')
      getList()
    } catch (error) {
      console.error('核实失败：', error)
    }
  })
}

// 取消
const handleCancel = (row) => {
  ElMessageBox.confirm(
    '确认要取消该充值记录吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await request.post('/black-card/recharge/cancel', {
        recharge_id: row.recharge_id
      })
      ElMessage.success('取消成功')
      getList()
    } catch (error) {
      console.error('取消失败：', error)
    }
  })
}

// 详情
const handleDetail = (row) => {
  router.push({
    name: 'RechargeDetail',
    query: { id: row.recharge_id }
  })
}

// 充值
const handleRecharge = (row) => {
  router.push({
    name: 'RechargeForm',
    query: { 
      card_no: row.black_card_no,
      org_id: row.org_id
    }
  })
}

// 操作成功回调
const handleSuccess = () => {
  getList()
}

// 初始化
getList()
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.search-wrapper {
  margin-bottom: 20px;
  max-width: 1000px;
  margin-left: auto;
  margin-right: auto;
}

.table-wrapper {
  margin-bottom: 20px;
  max-width: 1000px;
  margin-left: auto;
  margin-right: auto;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

:deep(.el-table) {
  margin-top: 20px;
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 16px;
}
</style> 